import {
	Row,
	Col,
	Transfer,
	Flex,
	Typography,
	Form,
	Input,
	Button,
	message,
} from "antd";
import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { userGroupAdd, userGroupInfo, userTagList } from "../service/user";

export default function UserAddCrowd() {
	const navigate = useNavigate();
	const { id } = useParams(); // 获取路由参数中的id
	const isEditing = id !== undefined; // 根据id是否存在判断是编辑还是添加
	const [form] = Form.useForm();
	const [title, setTitle] = useState(isEditing ? "编辑人群" : "新建人群");

	// 穿梭机数据
	const [mockData, setMockData] = useState([]);
	const [targetKeys, setTargetKeys] = useState(
		mockData.filter((item) => item.chosen).map((item) => item.key)
	);
	useEffect(() => {
		(async () => {
			const res = await userTagList();
			console.log(res);
			const arr = [];
			for (let key in res.data) {
				res.data[key].forEach((item) => {
					arr.push({
						key: item.tagLibraryBO.id,
						title: item.tagLibraryBO.tagName,
						chosen: false,
					});
				});
			}
			setMockData(arr);
		})();
		// 判断编辑还是添加
		if (isEditing) {
			// 通过id查询详情
			(async () => {
				const res = await userGroupInfo(id);
				console.log(res);
				// 将查询的数据赋给表单
				form.setFieldsValue(res.data);
				// 设置穿梭框的默认选中
				const arr = res.data.tagIds.split(",").map((item) => {
					return Number(item);
				});
				setTargetKeys(arr);
			})();
		} else {
		}
	}, []);

	// 提交表单
	const handleSubmit = async () => {
		const data = {
			id,
			tagIds: targetKeys.join(","),
			...form.getFieldsValue(),
		};

		const res = await userGroupAdd(data);
		if (res.success) {
      message.success(isEditing ? "编辑成功" : "新增成功");
      setTimeout(() => {
        navigate("/admin/user/crowd");
      }, 1000);
		}
	};
	return (
		<>
			<Row className="info">
				<Col span={24}>
					<Flex justify={"space-between"}>
						<Typography.Title level={3}>{title}</Typography.Title>
					</Flex>
				</Col>
			</Row>
			<Form
				labelCol={{
					span: 2,
				}}
				wrapperCol={{
					span: 12,
				}}
				style={{ width: "100%", marginTop: 30 }}
				onFinish={(values) => {
					values.tagIds = "";
					// 获取id，并用逗号分开
					targetKeys.forEach((item) => {
						values.tagIds += item + ",";
					});
					values.tagIds = values.tagIds.substring(
						0,
						values.tagIds.length - 1
					);
					// 判断是编辑还是添加
					if (isEditing) {
						(async () => {})();
					} else {
						// 新增
						(async () => {
							const res = await userGroupAdd(values);
							console.log(res);
							if (res.code === "0") {
								message.success("新增成功");
								setTimeout(() => {
									navigate("/admin/user/crowd");
								}, 1000);
							}
						})();
					}
				}}
				form={form}
			>
				<Row className="container" style={{ marginBottom: 0 }}>
					<Col span={24}>
						<Typography.Title level={4}>基本信息</Typography.Title>
					</Col>
					<Col span={24}>
						<Form.Item
							label="人群名称"
							name="groupName"
							rules={[
								{ required: true, message: "请输入人群名称" },
							]}
						>
							<Input
								maxLength={30}
								showCount
								placeholder="请输入人群名称 "
								style={{ width: 500 }}
							/>
						</Form.Item>
						<Form.Item label="人群介绍">
							<Input.TextArea
								maxLength={100}
								showCount
								style={{ width: 500, height: 100 }}
							/>
						</Form.Item>
					</Col>
				</Row>
				<Row
					className="container"
					style={{ marginTop: 0, marginBottom: 0 }}
				>
					<Col span={24}>
						<Typography.Title level={4}>人群特征</Typography.Title>
					</Col>
					<Col span={24}>
						<Row>
							<Col
								span={13}
								offset={1}
								style={{ display: "flex" }}
							>
								<Transfer
									dataSource={mockData}
									showSearch
									titles={["标签", "标签"]}
									targetKeys={targetKeys}
									onChange={(newValue) => {
										console.log(newValue);
										setTargetKeys(newValue);
									}}
									render={(item) => item.title}
								/>
							</Col>
						</Row>
					</Col>
				</Row>
				<Row
					className="container"
					style={{ marginTop: 0, marginBottom: 0 }}
				>
					<Col span={24}>
						<Form.Item label="预估人数" name="userNumber">
							<Input style={{ width: 200, marginRight: 10 }} />
						</Form.Item>
					</Col>
				</Row>
				<Row
					className="container"
					style={{ marginTop: 0, paddingBottom: 100 }}
				>
					<Col span={4} offset={1}>
						<Button
							type="primary"
							htmlType="submit"
							onClick={handleSubmit}
						>
							确定
						</Button>
						{/* 重置按钮 */}
						<Button style={{ marginLeft: 10 }} htmlType="reset">
							重置
						</Button>
					</Col>
				</Row>
			</Form>
		</>
	);
}
